# coding:utf-8
from pathlib import Path
from typing import Union

from PyQt6.QtCore import Qt, pyqtSignal, QSize
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import QFileDialog, QWidget, QHBoxLayout, QLabel, QSizePolicy
from qfluentwidgets import ExpandSettingCard, FluentIcon as FIF, PushButton, Dialog, ToolButton, BodyLabel
from qfluentwidgets.components.settings.folder_list_setting_card import FolderItem


class FileItem(QWidget):
    """ file item """

    removed = pyqtSignal(QWidget)

    def __init__(self, file, parent=None):
        super().__init__(parent=parent)
        self.file = file
        self.hBoxLayout = QHBoxLayout(self)
        self.fileLabel = BodyLabel(file, self)
        self.removeButton = ToolButton(FIF.CLOSE, self)

        self.removeButton.setFixedSize(39, 29)
        self.removeButton.setIconSize(QSize(12, 12))

        self.setFixedHeight(53)
        self.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Fixed)
        self.hBoxLayout.setContentsMargins(48, 0, 60, 0)
        self.hBoxLayout.addWidget(self.fileLabel, 0, Qt.AlignmentFlag.AlignLeft)
        self.hBoxLayout.addSpacing(16)
        self.hBoxLayout.addStretch(1)
        self.hBoxLayout.addWidget(self.removeButton, 0, Qt.AlignmentFlag.AlignRight)
        self.hBoxLayout.setAlignment(Qt.AlignmentFlag.AlignVCenter)

        self.removeButton.clicked.connect(lambda: self.removed.emit(self))


class FileListSettingCard(ExpandSettingCard):
    fileChanged = pyqtSignal(list)

    def __init__(self, icon: Union[str, QIcon, FIF], title: str, directory: str, parent=None):
        super().__init__(icon, title, '', parent)
        self._dialogDirectory = directory
        self.addFileButton = PushButton('添加文件', self, FIF.FOLDER_ADD)
        self.files = []
        self.__initWidget()

    def __initWidget(self):
        self.addWidget(self.addFileButton)
        # 初始化布局
        self.viewLayout.setSpacing(0)
        self.viewLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.viewLayout.setContentsMargins(0, 0, 0, 0)
        for file in self.files:
            self.__addFileItem(file)

        self.addFileButton.clicked.connect(self.__showFolderDialog)

    def __addFileItem(self, file: str):
        """ 添加文件项 """
        item = FileItem(file, self.view)
        item.removed.connect(self.__removeFile)
        self.viewLayout.addWidget(item)
        item.show()
        self._adjustViewSize()

    def __showFolderDialog(self):
        """ 显示文件夹对话框 """
        files, _ = QFileDialog.getOpenFileNames(self, "选择文件", '', self._dialogDirectory)
        if not files:
            return
        for file in files:
            if file not in self.files:
                self.__addFileItem(file)
                self.files.append(file)
        self.fileChanged.emit(self.files)

    def __showConfirmDialog(self, item):
        """ show confirm dialog """
        name = Path(item.file).name
        title = self.tr('Are you sure you want to delete the folder?')
        content = self.tr("If you delete the ") + f'"{name}"' + \
                  self.tr(" folder and remove it from the list, the folder will no "
                          "longer appear in the list, but will not be deleted.")
        w = Dialog(title, content, self.window())
        w.yesSignal.connect(lambda: self.__removeFile(item))
        w.exec()

    def __removeFile(self, item):
        """ remove folder """
        if item.file not in self.files:
            return

        self.files.remove(item.file)
        self.viewLayout.removeWidget(item)
        item.deleteLater()
        self._adjustViewSize()

        self.fileChanged.emit(self.files)

    def setAddText(self, text: str):
        self.addFileButton.setText(text)
